--
--    Health Organizer (http://sourceforge.net/projects/hor/,
--                      http://hor.sourceforge.net/)
--    Copyright (C) 2015-2017  Andrea Urbani ( matfanjol@users.sf.net )
--
--    This program is free software: you can redistribute it and/or modify
--    it under the terms of the GNU General Public License as published by
--    the Free Software Foundation, either version 3 of the License, or
--    (at your option) any later version.
--
--    This program is distributed in the hope that it will be useful,
--    but WITHOUT ANY WARRANTY; without even the implied warranty of
--    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
--    GNU General Public License for more details.
--
--    You should have received a copy of the GNU General Public License
--    along with this program.  If not, see <http://www.gnu.org/licenses/>.
--
SET statement_timeout = 0;
SET lock_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SET check_function_bodies = false;
SET client_min_messages = warning;
-- ----------
-- Removed the 
-- 'E ' = empty stomach
-- 'F ' = full stomach
-- '==' = no matter
-- types of "When" field of "tDrugsPrescriptions"
drop table if exists "tDrugsPrescriptions_DeletedV5" cascade;
create table "tDrugsPrescriptions_DeletedV5" as
select *
from "tDrugsPrescriptions"
where 
"When" in ('E ','F ','==');
update "tDrugs"
set "ID_DrugPrescription" = null
where "ID_DrugPrescription" in (select "ID" from "tDrugsPrescriptions_DeletedV5");
delete from "tDrugsPrescriptions"
where 
"When" in ('E ','F ','==');
-- --------
-- I have to check in the sources if the tDrugsPrescriptions_DeletedV5
-- is empty or not. If it is, a warning message has to appear
-- --------
ALTER TABLE "tDrugsPrescriptions"
   ALTER COLUMN "WhenTime" TYPE time without time zone;
create or replace function "fSettingsPatients_GetTime" ("_IdPatient" "tPersons"."ID"%TYPE, "_Kind" char(1) )
returns "tSettings"."Time_Breakfast"%TYPE
as $$
BEGIN
  DECLARE
    dbTime "tSettings"."Time_Breakfast"%TYPE;
    dbTimeWakeUp "tSettings"."Time_WakeUp"%TYPE;
    dbTimeBreakfast "tSettings"."Time_Breakfast"%TYPE;
    dbTimeMiddleMorning "tSettings"."Time_MiddleMorning"%TYPE;
    dbTimeLunch "tSettings"."Time_Lunch"%TYPE;
    dbTimeMiddleAfternoon "tSettings"."Time_MiddleAfternoon"%TYPE;
    dbTimeDinner "tSettings"."Time_Dinner"%TYPE;
    dbTimeSleep "tSettings"."Time_Sleep"%TYPE;
  BEGIN
    select
      "Time_WakeUp",
      "Time_Breakfast",
      "Time_MiddleMorning",
      "Time_Lunch",
      "Time_MiddleAfternoon",
      "Time_Dinner",
      "Time_Sleep"
     into dbTimeWakeUp,
       dbTimeBreakfast,
       dbTimeMiddleMorning,
       dbTimeLunch,
       dbTimeMiddleAfternoon,
       dbTimeDinner,
       dbTimeSleep
     from "tPatients"
     where
       "ID_Person"="_IdPatient";
    if ( "_Kind" = 'W' ) then
	  dbTime := dbTimeWakeUp;
    elsif ( "_Kind" = 'B' ) then
	  dbTime := dbTimeBreakfast;
    elsif ( "_Kind" = 'M' ) then
	  dbTime := dbTimeMiddleMorning;
    elsif ( "_Kind" = 'L' ) then
	  dbTime := dbTimeLunch;
    elsif ( "_Kind" = 'A' ) then
	  dbTime := dbTimeMiddleAfternoon;
    elsif ( "_Kind" = 'D' ) then
 	  dbTime := dbTimeDinner;
    elsif ( "_Kind" = 'S' ) then
	  dbTime := dbTimeSleep;
    else
	-- Unknown request
	return null;
    end if;
    if ( dbTime is null ) then
	-- I have to try the standard on of the settings
        select
          "Time_WakeUp",
          "Time_Breakfast",
          "Time_MiddleMorning",
          "Time_Lunch",
          "Time_MiddleAfternoon",
          "Time_Dinner",
          "Time_Sleep"
        into dbTimeWakeUp,
             dbTimeBreakfast,
             dbTimeMiddleMorning,
             dbTimeLunch,
             dbTimeMiddleAfternoon,
             dbTimeDinner,
             dbTimeSleep
        from "tSettings"
        where
          "ID"=1;
      if ( "_Kind" = 'W' ) then
	  dbTime := dbTimeWakeUp;
      elsif ( "_Kind" = 'B' ) then
	  dbTime := dbTimeBreakfast;
      elsif ( "_Kind" = 'M' ) then
	  dbTime := dbTimeMiddleMorning;
      elsif ( "_Kind" = 'L' ) then
	  dbTime := dbTimeLunch;
      elsif ( "_Kind" = 'A' ) then
	  dbTime := dbTimeMiddleAfternoon;
      elsif ( "_Kind" = 'D' ) then
   	  dbTime := dbTimeDinner;
      elsif ( "_Kind" = 'S' ) then
	    dbTime := dbTimeSleep;
      else
  	-- Unknown request
  	return null;
      end if;
    end if;
    return dbTime;
  END;
END;
$$
LANGUAGE plpgsql;
comment on function "fSettingsPatients_GetTime" ("tPersons"."ID"%TYPE, char(1)) is 'Returns the standard breakfast/lunch/dinner time.
_Kind is one of the following:
W = Wake up
B = Breackfast
M = Middle morning
L = Lunch
A = Middle afternoon
D = Dinner
S = Sleep';
create or replace function "fDrugsPrescriptions_GetStart" ("_ID" "tDrugsPrescriptions"."ID"%TYPE)
RETURNS timestamp without time zone
as $$
BEGIN
  DECLARE 
    dbID_Patient    "tDrugsPrescriptions"."ID_Patient"%TYPE;
	dbStartWhen     "tDrugsPrescriptions"."StartWhen"%TYPE;
	dbStartDate     "tDrugsPrescriptions"."StartDate"%TYPE;
	dbID_DrugPrescription "tDrugsPrescriptions"."ID_DrugPrescription"%TYPE;
	dbWhen	"tDrugsPrescriptions"."When"%TYPE;
	dbWhenTime	"tDrugsPrescriptions"."WhenTime"%TYPE;
	dbWhenBeforeAfter_Type	"tDrugsPrescriptions"."WhenBeforeAfter_Type"%TYPE;
	dbWhenBeforeAfter_Quantity	"tDrugsPrescriptions"."WhenBeforeAfter_Quantity"%TYPE;
	ReferenceTime time;
	StartDate date;
	StartDateTime timestamp without time zone;
	Sign integer;
  BEGIN
    select
	  "ID_Patient",
	  "StartWhen",
	  "StartDate",
	  "ID_DrugPrescription",
	  "When",
	  "WhenTime",
	  "WhenBeforeAfter_Type",
	  "WhenBeforeAfter_Quantity"
	  into dbID_Patient,
	       dbStartWhen,
	       dbStartDate,
		   dbID_DrugPrescription,
		   dbWhen,
		   dbWhenTime,
		   dbWhenBeforeAfter_Type,
		   dbWhenBeforeAfter_Quantity
	from "tDrugsPrescriptions"
	where "ID"="_ID";
    if ( dbID_Patient is null ) then
	  -- The prescription does not exist
  	  return null;
	end if;
	if ( dbStartWhen = 'D' ) then
	  -- Starts the given date
	  StartDate := dbStartDate;
  	elsif ( dbStartWhen = 'P' ) then
	  -- Starts at the end of another prescription
	  StartDate := "fDrugsPrescriptions_GetEnd"( dbID_DrugPrescription );
	else
	  -- Unknown start indication
	  return null;
	end if;
	if ( dbWhenTime is not null ) then
	  ReferenceTime := dbWhenTime;
	else
	  Sign := 0;
	  if ( dbWhen = 'W ' ) then
	    -- At wake up
	    ReferenceTime := "fSettingsPatients_GetTime"(dbID_Patient, 'W');
	  elsif ( ( dbWhen = 'BB' ) or ( dbWhen = 'BD' ) or ( dbWhen = 'BA' ) ) then
	    -- Before / at / after  break fast
	    ReferenceTime := "fSettingsPatients_GetTime"(dbID_Patient, 'B');
		if ( dbWhen = 'BB' ) then
		  Sign := -1;
		elsif ( dbWhen = 'BA' ) then
		  Sign := +1;
		end if;
	  elsif ( dbWhen = 'MM' ) then
	    -- Middle of the morning
	    ReferenceTime := "fSettingsPatients_GetTime"(dbID_Patient, 'M');
	  elsif ( ( dbWhen = 'LB' ) or ( dbWhen = 'LD' ) or ( dbWhen = 'LA' ) ) then
	    -- Before / at / after  lunch
	    ReferenceTime := "fSettingsPatients_GetTime"(dbID_Patient, 'L');
		if ( dbWhen = 'LB' ) then
		  Sign := -1;
		elsif ( dbWhen = 'LA' ) then
		  Sign := +1;
		end if;
	  elsif ( dbWhen = 'MA' ) then
	    -- Middle of the afternoon
	    ReferenceTime := "fSettingsPatients_GetTime"(dbID_Patient, 'A');
	  elsif ( ( dbWhen = 'DB' ) or ( dbWhen = 'DD' ) or ( dbWhen = 'DA' ) ) then
	    -- Before / at / after dinner
	    ReferenceTime := "fSettingsPatients_GetTime"(dbID_Patient, 'D');
		if ( dbWhen = 'DB' ) then
		  Sign := -1;
		elsif ( dbWhen = 'DA' ) then
		  Sign := +1;
		end if;
	  elsif ( dbWhen = 'S' ) then
	    -- Before to go to sleep
	    ReferenceTime := "fSettingsPatients_GetTime"(dbID_Patient, 'S');
		Sign := -1;
	  else
        -- Unknown
        return null;
      end if;
	  -- Now I evaluate the after/before settings
	  if ( dbWhenBeforeAfter_Type = 'M' ) then
	    -- X minutes
		select ReferenceTime + (Sign * dbWhenBeforeAfter_Quantity * interval '1 minute') into ReferenceTime;
	  elsif ( dbWhenBeforeAfter_Type = 'H' ) then
	    -- X hours
		select ReferenceTime + (Sign * dbWhenBeforeAfter_Quantity * interval '1 hour') into ReferenceTime;
	  end if;
	end if;
	select StartDate + ReferenceTime into StartDateTime;
	return StartDateTime;
  END;
END;
$$
LANGUAGE plpgsql;
comment on function "fDrugsPrescriptions_GetStart" ("_ID" "tDrugsPrescriptions"."ID"%TYPE) is 'Returns the start date time of the given prescription of drug. It no start is available, null is returned.';
create or replace function "fDrugsPrescriptions_GetEnd" ("_ID" "tDrugsPrescriptions"."ID"%TYPE)
RETURNS timestamp without time zone
as $$
BEGIN
  DECLARE 
	dbEndWhen     "tDrugsPrescriptions"."EndWhen"%TYPE;
	dbEndDate     "tDrugsPrescriptions"."EndDate"%TYPE;
	dbEndQuantity "tDrugsPrescriptions"."EndQuantity"%TYPE;
	dbWhen	"tDrugsPrescriptions"."When"%TYPE;
	dbEveryType	"tDrugsPrescriptions"."EveryType"%TYPE;
	dbEveryQuantity	"tDrugsPrescriptions"."EveryQuantity"%TYPE;
	EndDateTime timestamp without time zone;
  BEGIN
    EndDateTime = "fDrugsPrescriptions_GetStart"("_ID");
	if ( EndDateTime is not null ) then
		select
		  "EveryType",
		  "EveryQuantity",
		  "EndWhen",
		  "EndQuantity",
		  "EndDate"
		  into
		  dbEveryType,
		  dbEveryQuantity,
		  dbEndWhen,
		  dbEndQuantity,
		  dbEndDate
		from "tDrugsPrescriptions"
		where "ID"="_ID";
		if ( dbEndWhen = 'N' ) then
		  -- Never ends
          EndDateTime := null;
		elsif ( dbEndWhen = 'D' ) then
		  -- Ends the given date/time
		  EndDateTime := dbEndDate;
		elsif ( dbEndWhen = 'Q' ) then
		  -- Ends after the given quantity
		  if ( dbEveryType = 'H' ) then
			EndDateTime := EndDateTime + dbEndQuantity * dbEveryQuantity * interval '1 hour';
		  elsif ( dbEveryType = 'D' ) then
			EndDateTime := EndDateTime + dbEndQuantity * dbEveryQuantity * interval '1 day';
		  elsif ( dbEveryType = 'W' ) then
			EndDateTime := EndDateTime + dbEndQuantity * dbEveryQuantity * interval '1 week';
		  elsif ( dbEveryType = 'M' ) then
			EndDateTime := EndDateTime + dbEndQuantity * dbEveryQuantity * interval '1 month';
		  elsif ( dbEveryType = 'Y' ) then
			EndDateTime := EndDateTime + dbEndQuantity * dbEveryQuantity * interval '1 year';
		  else
			-- Unknow type
			EndDateTime := null;
		  end if;
		else
		  -- Unknown setting
		  EndDateTime := null;
		end if;
	end if;
	return EndDateTime;
  END;
END
$$
LANGUAGE plpgsql;
comment on function "fDrugsPrescriptions_GetEnd" ("_ID" "tDrugsPrescriptions"."ID"%TYPE) is 'Returns the end date time of the given prescription of drug. If it can''t be determinated, null is returned';
create or replace function "fDrugsPrescriptions_Explode" ("_ID" "tDrugsPrescriptions"."ID"%TYPE,
"_StartDate" "tDrugsPrescriptions"."StartDate"%TYPE,
"_EndDate" "tDrugsPrescriptions"."StartDate"%TYPE)
RETURNS TABLE (
"ID" "tDrugsPrescriptions"."ID"%TYPE,
"Date" "tDrugsPrescriptions"."StartDate"%TYPE )
AS $$
BEGIN
  DECLARE
	dbEveryType  	"tDrugsPrescriptions"."EveryType"%TYPE;
	dbEveryQuantity "tDrugsPrescriptions"."EveryQuantity"%TYPE;
	StartDate "tDrugsPrescriptions"."StartDate"%TYPE;
	EndDate "tDrugsPrescriptions"."EndDate"%TYPE;
BEGIN
  select
    "fDrugsPrescriptions_GetStart"("tDrugsPrescriptions"."ID"),
    "fDrugsPrescriptions_GetEnd"("tDrugsPrescriptions"."ID"),
	"EveryType",
	"EveryQuantity"
  into
    StartDate,
	EndDate,
	dbEveryType,
	dbEveryQuantity
  from "tDrugsPrescriptions"
  where "tDrugsPrescriptions"."ID"="_ID";
  if ( ( "_StartDate" > EndDate ) or
       ( "_EndDate" < StartDate ) ) then
    return;
  else
    "ID" := "_ID";
	"Date" := StartDate;
    loop
	   if ( ( "Date" >= "_StartDate" ) and
	        ( "Date" <= "_EndDate" ) ) then
	     return next;
	   end if;	
		if ( dbEveryType = 'H' ) then
		  "Date" := "Date" + dbEveryQuantity * interval '1 hour';
		elsif ( dbEveryType = 'D' ) then
		  "Date" := "Date" + dbEveryQuantity * interval '1 day';
		elsif ( dbEveryType = 'W' ) then
		  "Date" := "Date" + dbEveryQuantity * interval '1 week';
		elsif ( dbEveryType = 'M' ) then
		  "Date" := "Date" + dbEveryQuantity * interval '1 month';
		elsif ( dbEveryType = 'Y' ) then
		  "Date" := "Date" + dbEveryQuantity * interval '1 year';
		else
		  -- Unknow type
		  exit;
		end if;
		exit when ( ( "Date" > EndDate ) or
		            ( "Date" > "_EndDate" ) );
    end loop;
  end if;
END;
END;
$$
LANGUAGE plpgsql;
comment on function "fDrugsPrescriptions_Explode" ("tDrugsPrescriptions"."ID"%TYPE,"tDrugsPrescriptions"."StartDate"%TYPE,"tDrugsPrescriptions"."StartDate"%TYPE) is 'Returns the list of the occourences of the given prescription of drugs within the given interval';
-- ----
alter table "tDocumentsFiles"
  add column "FileDateTime" timestamp without time zone;
update "tDocumentsFiles"
set "FileDateTime"=localtimestamp;
alter table "tDocumentsFiles"
alter column "FileDateTime" set not null;
CREATE TABLE "tLogs"
(
   "ID" serial NOT NULL, 
   "Date" time without time zone NOT NULL DEFAULT localtimestamp, 
   "ID_Person" integer, 
   "Kind" character(1) NOT NULL, 
   "Message" character varying(50) NOT NULL, 
   "Details" text, 
   "ReferenceKey" integer, 
   "Version" integer NOT NULL DEFAULT 1, 
   CONSTRAINT "pk_tLogs" PRIMARY KEY ("ID"), 
   CONSTRAINT "chk_tLogs_Kind" CHECK ("Kind" in ('I','U','D','S')), 
   CONSTRAINT "fk_tLogs_tPersons" FOREIGN KEY ("ID_Person") REFERENCES "tPersons" ("ID") ON UPDATE CASCADE ON DELETE SET NULL
);
COMMENT ON COLUMN public."tLogs"."ID_Person" IS 'Link to the patient, if applicable';
COMMENT ON COLUMN public."tLogs"."Kind" IS 'Kind of the operation that generates the log:
I = Insertion of new data
U = Update of existing data
D = Delete of existing data
S = Substitution of data
';
COMMENT ON COLUMN "tLogs"."Message" IS 'The log message';
COMMENT ON COLUMN "tLogs"."Details" IS 'Details of the log';
COMMENT ON COLUMN "tLogs"."ReferenceKey" IS 'Reference key (when applicable)';
COMMENT ON COLUMN "tLogs"."Version" IS 'Version of the used logging method';
COMMENT ON TABLE "tLogs"
  IS 'Stores the logs of some operations done by the user';
-- 
ALTER TABLE "tDocumentsFiles"
  ADD "DrugBox" boolean not null default false;
comment on column "tDocumentsFiles"."DrugBox" is 'When true, this document contains the picture of the external box/package that contains a drug';
ALTER TABLE "tDocumentsFiles"
  ADD "DrugPicture" boolean not null default false;
comment on column "tDocumentsFiles"."DrugPicture" is 'When true, this document contains the picture of a drug';
ALTER TABLE "tDocumentsFiles"
  ADD "DrugInstructions" boolean not null default false;
comment on column "tDocumentsFiles"."DrugInstructions" is 'When true, this document contains the picture/document with the instructions/descriptions of a drug';
ALTER TABLE "tDocumentsFiles"
  add constraint "ck_tDocumentsFiles_DrugFlags"
    check (
( not ( "DrugBox" and "DrugPicture" ) ) and
( not ( "DrugBox" and "DrugInstructions" ) ) and
( not ( "DrugInstructions" and "DrugPicture" ) )
);
-- -----------
CREATE TABLE "tAgendaDrugs"
(
   "ID" serial NOT NULL, 
   "ID_Patient" integer NOT NULL, 
   "DateTime" time without time zone NOT NULL, 
   "ID_DrugPrescription" integer, 
   "Status" character(1) not null, 
   "ID_Drug" integer not null,
   "Note" text,
   CONSTRAINT "pk_tAgendaDrugs" PRIMARY KEY ("ID"), 
   CONSTRAINT "fk_tAgendaDrugs_tPatients" FOREIGN KEY ("ID_Patient") REFERENCES "tPatients" ("ID_Person") ON UPDATE CASCADE ON DELETE CASCADE, 
   CONSTRAINT "fk_tAgendaDrugs_tDrugsPrescriptions" FOREIGN KEY ("ID_DrugPrescription") REFERENCES "tDrugsPrescriptions" ("ID") ON UPDATE CASCADE ON DELETE CASCADE, 
   CONSTRAINT "fk_tAgendaDrugs_tDrugs" FOREIGN KEY ("ID_Drug") REFERENCES "tDrugs" ("ID") ON UPDATE CASCADE ON DELETE CASCADE,
   CONSTRAINT "ck_tAgendaDrugs_Status" CHECK ("Status" in ('T','K','S') )
);
comment on column "tAgendaDrugs"."Status" is 'T = To take
K = taKen
S = Skipped';
create index "idx_tAgendaDrugs_PatientDate" on "tAgendaDrugs" ("ID_Patient","DateTime");
create index "idx_tAgendaDrugs_PatientDateStatus" on "tAgendaDrugs" ("ID_Patient","DateTime","Status");
CREATE TABLE "tAgendaExaminations"
(
   "ID" serial NOT NULL, 
   "ID_Patient" integer NOT NULL, 
   "DateTime" time without time zone NOT NULL, 
   "ID_ExaminationPeriodical" integer, 
   "Status" character(1) not null, 
   "ID_Examination" integer not null, 
   "Note" text,
   CONSTRAINT "pk_tAgendaExaminations" PRIMARY KEY ("ID"), 
   CONSTRAINT "fk_tAgendaExaminations_tPatients" FOREIGN KEY ("ID_Patient") REFERENCES "tPatients" ("ID_Person") ON UPDATE CASCADE ON DELETE CASCADE, 
   CONSTRAINT "fk_tAgendaExaminations_tExaminationsPeriodical" FOREIGN KEY ("ID_ExaminationPeriodical") REFERENCES "tExaminationsPeriodical" ("ID") ON UPDATE CASCADE ON DELETE CASCADE,
   CONSTRAINT "fk_tAgendaExaminations_tExaminations" FOREIGN KEY ("ID_Examination") REFERENCES "tExaminations" ("ID") ON UPDATE CASCADE ON DELETE CASCADE,
   CONSTRAINT "ck_tAgendaExaminations_Status" CHECK ("Status" in ('B','T','C','D','M'))
);
comment on column "tAgendaExaminations"."Status" is 'B = to Book
T = booked: To do
C = Cancelled
D = Done
M = Moved to another date/Time';
create index "idx_tAgendaExaminations_PatientDate" on "tAgendaExaminations" ("ID_Patient","DateTime");
create index "idx_tAgendaExaminations_PatientDateStatus" on "tAgendaExaminations" ("ID_Patient","DateTime","Status");
CREATE TABLE "tAgendaCategories"
(
   "ID" serial NOT NULL, 
   "Name" varchar(45) not null,
   "Picture" bytea,
   CONSTRAINT "pk_tAgendaCategories" PRIMARY KEY ("ID")
);
CREATE TABLE "tAgendaFree"
(
   "ID" serial NOT NULL, 
   "ID_Patient" integer NOT NULL, 
   "DateTime" time without time zone NOT NULL, 
   "ID_AgendaCategory" integer not null,
   "Title" varchar(45) not null,
   "Note" text,
   CONSTRAINT "pk_tAgendaFree" PRIMARY KEY ("ID"), 
   CONSTRAINT "fk_tAgendaFree_tPatients" FOREIGN KEY ("ID_Patient") REFERENCES "tPatients" ("ID_Person") ON UPDATE CASCADE ON DELETE CASCADE, 
   CONSTRAINT "fk_tAgendaFree_tAgendaCategories" FOREIGN KEY ("ID_AgendaCategory") REFERENCES "tAgendaCategories" ("ID") ON UPDATE CASCADE ON DELETE CASCADE
);
create index "idx_tAgendaFree_PatientDate" on "tAgendaFree" ("ID_Patient","DateTime");
CREATE TABLE "tProsthesisCompanies"
(
  "ID" serial NOT NULL,
  "Name" character varying(45) NOT NULL,
  "Note" text,
  "Expired" boolean NOT NULL DEFAULT false,
  "Origin" character varying(15),
  CONSTRAINT "pk_tProthesisCompanies" PRIMARY KEY ("ID"),
  constraint "uk_tProthesisCompanies_Name" unique ("Name")
);
create table "tProsthesisTypes" (
	"ID" serial not null,
	"Type" char(1) not null,
	"ID_ProsthesisCompany" integer,
	"Model" character varying(45),
	"ID_Document" integer,
	"Note" text,
	"Origin" character varying(15),
	constraint "pk_tProsthesisTypes" primary key ("ID"),
	constraint "fk_tProsthesisTypes_tProsthesisCompanies" foreign key ("ID_ProsthesisCompany") references "tProsthesisCompanies" ("ID") on update cascade on delete cascade,
	constraint "fk_tProsthesisTypes_tDocuments" foreign key ("ID_Document") references "tDocuments" ("ID") on update cascade on delete restrict,
	constraint "uk_tProthesisTypes_CompanyModel" unique ("ID_ProsthesisCompany","Model")
);
create table "tProsthesisTypesAvoidExaminationsNames" (
	"ID_ProsthesisType" integer not null,
	"ID_ExaminationName" integer not null,
	"Note" text,
	constraint "pk_tProsthesisTypesAvoidExaminationsNames" primary key ("ID_ProsthesisType","ID_ExaminationName"),
	constraint "fk_tProsthesisTypesAvoidExaminationsNames_tProsthesisTypes" foreign key ("ID_ProsthesisType") references "tProsthesisTypes" ("ID") on update cascade on delete restrict,
	constraint "fk_tProsthesisTypesAvoidExaminationsNames_tExaminationsNames" foreign key ("ID_ExaminationName") references "tExaminationsNames" ("ID") on update cascade on delete restrict
);
create table "tProsthesis" (
	"ID" serial not null,
	"ID_Patient" integer not null,
	"ID_ProsthesisType" integer not null,
	"Date" timestamp without time zone,
	"SerialNumber" character varying(45),
	"ID_Hospitalization" integer,
	"Place" character varying(45),
	"Removed_Date" timestamp without time zone,
	"Removed_ID_Hospitalization" integer,
	"Note" text,
	constraint "pk_tProsthesis" primary key ("ID"),
	constraint "fk_tProsthesis_tPatients" foreign key ("ID_Patient") references "tPatients" ("ID_Person") on update cascade on delete cascade,
	constraint "fk_tProsthesis_tProsthesisTypes" foreign key ("ID_ProsthesisType") references "tProsthesisTypes" ("ID") on update cascade on delete restrict,
	constraint "fk_tProsthesis_tHospitalizations" foreign key ("ID_Hospitalization") references "tHospitalizations" ("ID") on update cascade on delete restrict,
	constraint "fk_tProsthesis_tHospitalizations_Removed" foreign key ("Removed_ID_Hospitalization") references "tHospitalizations" ("ID") on update cascade on delete restrict
);
-- -----
alter table "tSettings" add column
  "Updating" boolean not null default false;
-- ----------
update "tSettings"
set "DbVersion"=5
where "ID"=1;
